package com.zlj.jdbc.dateTimestamp;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.Test;

import com.zlj.jdbc.demo.JdbcUtils;

public class DateDemo {
	/**
	 * JDBC完成添加操作
	 * 
	 * java.util.Date 转换为 java.sql.Date、java.sql.Time、java.sql.Timestamp 的案例
	 * 
	 * @throws ClassNotFoundException
	 * @throws IOException
	 * @throws SQLException
	 */
	@Test
	public void test01() throws ClassNotFoundException, IOException, SQLException {
		Connection conn = null;
		PreparedStatement statement = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "insert into t_date values(?,?,?)";
			statement = conn.prepareStatement(sql);
			java.util.Date date = new java.util.Date();
			long time = date.getTime();
			statement.setDate(1, new java.sql.Date(time));
			statement.setTime(2, new java.sql.Time(time));
			statement.setTimestamp(3, new java.sql.Timestamp(time));
			statement.executeUpdate();
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
                if(conn != null) conn.close();
                if(statement != null) statement.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
	
	/**
	 * JDBC 执行查询操作
	 * java.sql.Date、java.sql.Time、java.sql.Timestamp  转换为  java.util.Date 的案例
	 */
	@Test
	public void test02() {
		Connection conn = null;
		PreparedStatement statement = null;
		ResultSet resultSet = null;
		try {
			conn = JdbcUtils.getConnection();
			String sql = "select * from t_date";
			statement = conn.prepareStatement(sql);
			resultSet = statement.executeQuery();
			while(resultSet.next()) {
				java.util.Date date1 = resultSet.getDate(1);
				java.util.Date date2 = resultSet.getDate(2);
				java.util.Date date3 = resultSet.getDate(3);
				System.out.println(date1 + "==" + date2 + "===" + date3);
				//2017-06-17==1970-01-01===2017-06-17
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
                if(conn != null) conn.close();
                if(statement != null) statement.close();
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}
